﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Smartec.Accounts.Camel.AMS.WebApp.Models;
using System.Web.Routing;
using System.Web.Security;
using Smartec.Accounts.Camel.AMS.Model.Entities;
using Smartec.Accounts.Camel.AMS.Model.Facades;

namespace Smartec.Accounts.Camel.AMS.WebApp.Controllers
{
    public class SystemRolesController : Controller
    {
        //
        // GET: /SiteRoles/
        [CustomAuthorize(Action = "View")]
        public ActionResult Index()
        {
            return View(Roles.GetAllRoles());
        }

        //
        // GET: /SiteRoles/Edit/5
        [CustomAuthorize(Action = "Edit")]
        public ActionResult Edit(string id)
        {
            ViewBag.Role = id;
            ViewBag.AllUsers = GetAllUsers(id);

            return View();
        }

        private List<KeyValuePair<string, KeyValuePair<string, bool>>> GetAllUsers(string roleName)
        {
            List<KeyValuePair<string, KeyValuePair<string, bool>>> usersList = new List<KeyValuePair<string, KeyValuePair<string, bool>>>();
            foreach (MembershipUser user in Membership.GetAllUsers())
            {
                SiteUser siteUser = SiteUserFacade.GetSiteUser((Guid)Membership.GetUser(user.UserName).ProviderUserKey);
                if (HttpContext.User.Identity.Name != user.UserName)
                {
                    usersList.Add(new KeyValuePair<string, KeyValuePair<string, bool>>(user.UserName, new KeyValuePair<string, bool>(siteUser.DisplayName, Roles.IsUserInRole(user.UserName, roleName))));
                }
            }
            return usersList;
        }

        //
        // POST: /SiteRoles/Edit/5

        [HttpPost]
        public ActionResult Edit(string id, FormCollection collection)
        {
            try
            {
                string roleusers = collection["roleuser"];
                List<string> roleusersList = new List<string>();
                if (!string.IsNullOrEmpty(roleusers))
                {
                    roleusersList = roleusers.Split(',').ToList();
                }

                List<string> originalRoleusers=new List<string>();
                string[] originalRoleusersArr= Roles.GetUsersInRole(id);
                if(originalRoleusersArr.Length>0 )
                {
                    originalRoleusers = originalRoleusersArr.Where(o => o != HttpContext.User.Identity.Name).ToList();
                }

                IEnumerable<string> removedRoleUsers = originalRoleusers.Where(o => !roleusersList.Contains(o));
                IEnumerable<string> addedRoleUsers = roleusersList.Where(o => !originalRoleusers.Any(t => t == o));

                if(removedRoleUsers.Count()>0)
                {
                    Roles.RemoveUsersFromRole(removedRoleUsers.ToArray(), id);
                }

                if (addedRoleUsers.Count() > 0)
                {
                    Roles.AddUsersToRole(addedRoleUsers.ToArray(), id);
                }

                Role role = RoleControllerFacade.GetRole(id);

                var count = role.RoleControllers.Count();
                for (var i = count - 1; i >= 0; i--)
                {
                    RoleControllerFacade.Delete(role.RoleControllers.ElementAt(i));
                }


                string controllers = collection["Controller_ID"];
                List<RoleController> roleControllers = new List<RoleController>();
                if (!string.IsNullOrEmpty(controllers))
                {
                    string[] controllersArr = controllers.Split(',');
                    string[] controllersView = collection["RCView"].Split(',');
                    string[] controllersAdd = collection["RCAdd"].Split(',');
                    string[] controllersEdit = collection["RCEdit"].Split(',');
                    string[] controllersDelete = collection["RCDelete"].Split(',');

                    for (int i = 0; i < controllersArr.Length; i++)
                    {
                        RoleController roleController = new RoleController();
                        roleController.Role_ID = role.RoleId;
                        roleController.Controller_ID = Convert.ToInt32(controllersArr[i]);
                        roleController.View = Convert.ToBoolean(controllersView[i]);
                        roleController.Add = Convert.ToBoolean(controllersAdd[i]);
                        roleController.Edit = Convert.ToBoolean(controllersEdit[i]);
                        roleController.Delete = Convert.ToBoolean(controllersDelete[i]);

                        role.RoleControllers.Add(roleController);
                    }
                }

                RoleControllerFacade.Save();

                return RedirectToAction("Index");
            }
            catch
            {
                ViewBag.Role = id;
                ViewBag.AllUsers = GetAllUsers(id);
                return View();
            }
        }

    }
}
